package com.duan.common.task;

import com.duan.common.beans.vo.SessionModel;
import com.duan.common.enums.ResponseENUM;
import com.duan.common.exceptions.ServiceException;
import com.duan.common.utils.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;


@Component
@Slf4j
public class ScheduleTask {


    /**
     * 清空Session定时任务
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void scheduleClearSession() {
        long beginClearSessionTime = System.currentTimeMillis();
        Map<String, SessionModel> sessionMap = SessionUtil.getSessionMap();
        Iterator<Map.Entry<String, SessionModel>> it = sessionMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, SessionModel> entry = it.next();
            String token = entry.getKey();
            log.info("ScheduleTask 当前存活的token:{}", token);
            SessionModel sessionModel = entry.getValue();
            if ((System.currentTimeMillis() - sessionModel.getTokenCreateTime()) > SessionUtil.sessionTimeOut) {
                it.remove();
                log.info("ScheduleTask 当前移除的token:{}", token);
            }
        }
        log.info("ScheduleTask 当前任务清除session缓存总耗时：{}", (System.currentTimeMillis() - beginClearSessionTime));
    }
}